package xps.and.uudaijia.userclient;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.facebook.stetho.Stetho;
import com.iflytek.cloud.Setting;
import com.iflytek.cloud.SpeechUtility;
import com.jude.utils.JUtils;
import com.squareup.leakcanary.LeakCanary;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.uphyca.stetho_realm.RealmInspectorModulesProvider;
import com.wenming.library.LogReport;
import com.wenming.library.save.imp.CrashWriter;
import com.wenming.library.upload.email.EmailReporter;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Flowable;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import xps.and.uudaijia.userclient.data.db.MyMigration;
import xps.and.uudaijia.userclient.service.RemoteService;
import xps.and.uudaijia.userclient.util.CommonUtils;
import xps.and.uudaijia.userclient.util.GlobalPositionInfo;
import xps.and.uudaijia.userclient.view.activity.LoginActivity;


public class App extends Application implements Handler.Callback, Application.ActivityLifecycleCallbacks {
    public Context mContext = null;
    private static App INSTANCE;
    public String mAppDir;
    public String mPicturesDir;
    public String mFilesDir;
    public GlobalPositionInfo globalPositionInfo;
    Handler handler = null;
    HashMap<String, SoftReference<Activity>> acsTemp = new HashMap<>();
    ArrayList<SoftReference<Activity>> activitiesCollected = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        globalPositionInfo = new GlobalPositionInfo(this);
        INSTANCE = this;
        SDKInitializer.initialize(this);
        handler = new Handler(getMainLooper(), this);

        JUtils.initialize(this);
        Realm.init(this);
        SpeechUtility.createUtility(this, "appid=" + "59891d55");
        Setting.setShowLog(false);

        //RealmConfiguration config = new RealmConfiguration.Builder().build();
        RealmConfiguration config = new RealmConfiguration.Builder().schemaVersion(0).migration(new MyMigration()).build();
        Realm.setDefaultConfiguration(config);

        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
                        .build());

        initAppDir();
        UMShareAPI.get(this);
        PlatformConfig.setWeixin("wx3595d9ebfe0bc446", "28f2c5f812b1073038a830891c218da1");
        PlatformConfig.setQQZone("1105806647", "x0Oqm1kvQcMdUFcu");
        Log.e("TAGG", CommonUtils.sHA1(this));

        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);

        PlatformConfig.setWeixin(Constants.APP_ID, Constants.SECRET);
        //讯飞语音
        SpeechUtility.createUtility(this, "appid=" + "594df794");
        Setting.setShowLog(false);
        initCrashReport();
        LogReport.getInstance().upload(this);
    }

    private void initCrashReport() {
        LogReport.getInstance()
                .setCacheSize(30 * 1024 * 1024)//支持设置缓存大小，超出后清空
                .setLogDir(getApplicationContext(), "sdcard/" + this.getString(this.getApplicationInfo().labelRes) + "/")//定义路径为：sdcard/[app name]/
                .setWifiOnly(false)//设置只在Wifi状态下上传，设置为false为Wifi和移动网络都上传
                .setLogSaver(new CrashWriter(getApplicationContext()))//支持自定义保存崩溃信息的样式
                //.setEncryption(new AESEncode()) //支持日志到AES加密或者DES加密，默认不开启
                .init(getApplicationContext());
        initEmailReporter();
    }

    /**
     * 使用EMAIL发送日志
     */
    private void initEmailReporter() {
        EmailReporter email = new EmailReporter(this);
        email.setReceiver("15811139099@163.com");//收件人
        email.setSender("790928421@qq.com");//发送人邮箱
        email.setSendPassword("yfkvycwrtiicbcbd");//邮箱的客户端授权码，注意不是邮箱密码
        email.setSMTPHost("smtp.qq.com");//SMTP地址
        email.setPort("465");//SMTP 端口
        LogReport.getInstance().setUploadType(email);
    }

    public GlobalPositionInfo getGloPosinfo() {
        return globalPositionInfo;
    }

    public static App getInstance() {
        return INSTANCE;
    }

    private void initAppDir() {
        File file = getExternalFilesDir(null);
        if (!file.exists()) {
            file.mkdirs();
        }

        mAppDir = file.getAbsolutePath();

        file = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!file.exists()) {
            file.mkdirs();
        }

        mPicturesDir = file.getAbsolutePath();

        file = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        if (!file.exists()) {
            file.mkdirs();
        }

        mFilesDir = file.getAbsolutePath();
    }

    public void showHintDialog() {
        SharedPreferences sp = JUtils.getSharedPreference();
        SharedPreferences.Editor spEd = sp.edit();
        spEd.putString("User_Access_token", "");
        spEd.putString("User_ID", "");
        spEd.putString("User_Name", "");
        spEd.putString("User_Phone", "");
        spEd.putString("User_Img", "");
        spEd.putBoolean("User_Login", false);
        spEd.commit();
        JPushInterface.setAliasAndTags(mContext, "", null, mAliasCallback);
        Intent Logintent = new Intent(mContext, LoginActivity.class);
        Logintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Logintent.putExtra("zhanghao", "1");
        startActivity(Logintent);
        Intent Serviceintent = new Intent(mContext, RemoteService.class);
        Serviceintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        stopService(Serviceintent);
    }

    public void exitApp() {
        Flowable.just(activitiesCollected).flatMap(Flowable::fromIterable)
                .filter(softAct -> softAct.get() != null && (!softAct.get().isFinishing() || !softAct.get().isDestroyed()))
                .forEach(softAct -> softAct.get().finish());
        showHintDialog();
    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success极光推送别名设置成功";
                    Log.i("mAliasCallback", logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.极光推送别名设置失败，60秒后重试";
                    Log.i("mAliasCallback", logs);
                    break;
                default:
                    logs = "极光推送设置失败，Failed with errorCode = " + code;
                    Log.e("mAliasCallback", logs);
                    break;
            }
        }
    };

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        activitiesCollected.add(new SoftReference<Activity>(activity));
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}
